<?php

/**
 * @Author: chenjianghui
 * @Date:   2018-08-07 15:56:40
 * @Last Modified by:   chenjianghui
 * @Last Modified time: 2018-08-08 09:48:55
 */
namespace app\common\model;

use app\common\model\User;
use think\Model;

class UserBindOauth extends model
{

    /*
     * 用户第三方信息信息保存
     * */
    public function add()
    {
        return $this->allowField(['source', 'nickname', 'oauth_sn', 'openid', 'come', 'on_time', 'sex', 'avatar'])->save();
    }

    /*
     * 绑定用户
     * */
    public function bindUser()
    {
        $this->on_time = time();
        return $this->allowField(['user_id', 'on_time'])->save();
    }

    /*
     * 判断是否绑定了账号
     * @params oauth_info object 第三方用户唯一标示id
     * @params source string 第三方简称
     * */
    public static function getBindUser($oauth_info, $source)
    {
        $sn       = $oauth_info['oauth_sn'];
        $ouathObj = self::where(['oauth_sn' => $sn, 'source' => $source])->find();
        $result   = [
            'userObj'       => '',
            'bind_oauth_id' => '',
        ];
        if ($ouathObj) {
            if ($ouathObj->user_id) {
                $userObj = User::get($ouathObj->user_id);
                $userObj->save(['avatar' => $oauth_info['avatar']]);
                $result['userObj'] = $userObj;
            } else {
                $result['bind_oauth_id'] = $ouathObj->id;
            }
            return $result;
        } else {
            $data = [
                'source'   => $source,
                'nickname' => $oauth_info['nickname'],
                'oauth_sn' => $oauth_info['oauth_sn'],
                'openid'   => $oauth_info['openid'],
                'come'     => $oauth_info['come'],
                'sex'      => $oauth_info['sex'],
                'avatar'   => $oauth_info['avatar'],
            ];

            $ouathObj = new UserBindOauth($data);
            if ($ouathObj->add()) {
                $result['bind_oauth_id'] = $ouathObj->id;
                return $result;
            }
        }
        return false;
    }
}
